﻿using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using DevExpress.XtraPrinting;
using HandyControl.Controls;
using PlaceOrder_Client.Models.Common;
using PlaceOrder_Client.Views;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Common;
using PlaceOrder_Shared.Models.Daily;
using Prism.DryIoc;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using static PlaceOrder_Client.ViewModels.OrderViewModel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using MessageBox = HandyControl.Controls.MessageBox;

namespace PlaceOrder_Client.ViewModels
{
    public class PingCangViewModel:Prism.Mvvm.BindableBase
    {

        #region 依赖属性
        private bool selectedOptionJia0 = true;

        /// <summary>
        /// +0 （默认加0）
        /// </summary>
        public bool SelectedOptionJia0
        {
            get { return selectedOptionJia0; }
            set { selectedOptionJia0 = value; RaisePropertyChanged(); }
        }

        private bool selectedOptionJia1 = false;

        /// <summary>
        /// +1 
        /// </summary>
        public bool SelectedOptionJia1
        {
            get { return selectedOptionJia1; }
            set { selectedOptionJia1 = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 加载显示的东西
        /// </summary>
        private string loadingMessage = "加载中...";

        public string LoadingMessage
        {
            get { return loadingMessage; }
            set { loadingMessage = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 加载中
        /// </summary>
        private bool isLoading;

        public bool IsLoading
        {
            get { return isLoading; }
            set { isLoading = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 接收人
        /// </summary>
        private string target;

        public string Target
        {
            get { return target; }
            set { target = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 选中的中介
        /// </summary>
        private ChatReceiver selectedReceiver;

        public ChatReceiver SelectedReceiver
        {
            get { return selectedReceiver; }
            set
            {
                selectedReceiver = value; RaisePropertyChanged(); if (selectedReceiver != null)
                {
                    this.Target = selectedReceiver.Target;
                }
            }
        }


        private ObservableCollection<ChatReceiver> chatReceivers;
        public ObservableCollection<ChatReceiver> ChatReceivers
        {
            get { return chatReceivers; }
            set
            {
                if (chatReceivers != value)
                {
                    chatReceivers = value;
                    RaisePropertyChanged();
                }
            }
        }

        private string title;

        public string Title
        {
            get { return title; }
            set { title = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 交易类型
        /// </summary>
        private string dealType;

        public string DealType
        {
            get { return dealType; }
            set { dealType = value; RaisePropertyChanged(); }
        }
        private string tsCode;
   
        public string TsCode
        {
            get { return tsCode; }
            set { tsCode = value; RaisePropertyChanged(); }
        }

        private decimal price;

        public decimal Price
        {
            get { return price; }
            set { price = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 最大平仓量
        /// </summary>
        private decimal maxVolume;

        public decimal MaxVolume
        {
            get { return maxVolume; }
            set { maxVolume = value; RaisePropertyChanged(); }
        }

        private decimal volume;

        public decimal Volume
        {
            get { return volume; }
            set { volume = value; RaisePropertyChanged(); }
        }


        private decimal floatBp;

        public decimal FloatBp
        {
            get { return floatBp; }
            set { floatBp = value; RaisePropertyChanged(); }
        }

        private DateTime deliveryDate;
        public DateTime DeliveryDate
        {
            get { return deliveryDate; }
            set { deliveryDate = value; RaisePropertyChanged(); }
        }

        public long? UserTradeID { get; set; }

        public PingCangLilyTrade OriginalUserTrade { get; set; }
        #endregion


        #region 命令
        public DelegateCommand ConfirmPingCangCommand { get; set; }
        #endregion

        public PingCangViewModel()
        {
            this.Title = $"{UserHelper.NickName}-平仓窗口-{this.TsCode}";
        }
        public event EventHandler<PingCangArgs> PingCangRequested;
        private readonly IDailyData _dailyData;

        public PingCangViewModel(PingCangLilyTrade userTrade,IDailyData dailyData)
        {
            _dailyData = dailyData;
            InitBroker();
            string suffix = userTrade?.DeliverySpeed?.Substring((int)(userTrade?.DeliverySpeed?.LastIndexOf('+')));  // 提取 "+1" 或 "+0"
            if(suffix=="+0")
            {
                this.SelectedOptionJia0=true;
            }else
            {
                this.SelectedOptionJia1 = true;
            }
            OriginalUserTrade = userTrade;
            OrderListViewModel.websocket.QuanYiOrderClientMessageEvent -= WebSocketHelper_QuanYiOrderClientMessageEvent;

            OrderListViewModel.websocket.QuanYiOrderClientMessageEvent += WebSocketHelper_QuanYiOrderClientMessageEvent;
            //对价单
            if (userTrade.Direction=="bond_0")
            {
                this.DealType="卖出";
            }
            else
            {
                this.DealType = "买入";
            }

            MaxVolume = decimal.Parse(userTrade.Volume);

       
            //var tempTsInfo = _dailyData.GetBondByCode(userTrade.Tscode);
            //this.Price = _dailyData.GetLatestPrice(tempTsInfo);
            this.Volume = decimal.Parse(userTrade.Volume);
            this.DeliveryDate = (DateTime)userTrade.DeliveryTime;
            this.TsCode=userTrade.Tscode;   
            this.FloatBp = 0.1M;//默认浮动0.1BP

    
            InitPriceAsync();
            
            //this.DealType=userTrade.DealType;
            //this.TsCode = userTrade.TsCode;
            //this.Price = userTrade.Price;
            //this.Volume = userTrade.Volume;
            //this.DeliveryDate = userTrade.DeliveryDate;

            //this.UserTradeID = userTrade.UserTradeID;
            InitCommand();

            Messenger.Default.Unregister<List<LilyOccupyBrokerInfo>>(this, MessageToken.OccupyBrokerInfo, HandleOccupyBrokerInfoMessage);
            Messenger.Default.Register<List<LilyOccupyBrokerInfo>>(this, MessageToken.OccupyBrokerInfo, HandleOccupyBrokerInfoMessage);
        }

        private object _brokerLock = new object();
        public List<BrokerInfo> BrokerInfosByLily = new List<BrokerInfo>();
        public List<BrokerInfo> OccupiedBroker { get; set; }
        private void HandleOccupyBrokerInfoMessage(List<LilyOccupyBrokerInfo> list)
        {
            lock (_brokerLock)
            {
                try
                {
                    // 获取所有需要禁用的 brokerid
                    BrokerInfosByLily = list.Select(o => new BrokerInfo
                    {
                        BrokerId = o.BrokerId,
                        Occupy = o.Occupy,
                        UserId = o.Occupyier
                    }).ToList();

                    //foreach (var item in BrokerInfosByLily)
                    //{
                    //    AppLog.WriteError("lily数据：" + item?.ToString());
                    //}

                    // 查找所有 occupy=true 且 UserId 等于当前用户的 brokers
                    var occupiedBrokers = BrokerInfosByLily.Where(b => b.Occupy && b.UserId == UserHelper.UserID).ToList();

                    if (occupiedBrokers.Any())
                    {
                        OccupiedBroker = occupiedBrokers;

                        // 只有自己能下单的情况
                        foreach (var receiver in ChatReceivers)
                        {
                            var info = BrokerInfosByLily.FirstOrDefault(b => b.BrokerId == receiver.Brokerid);
                            if (info != null)
                            {
                                if (occupiedBrokers.Any(b => b.BrokerId == info.BrokerId))
                                {
                                    PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                                    {
                                        this.SelectedReceiver = ChatReceivers.Where(o => o.Brokerid == info.BrokerId).FirstOrDefault();
                                        //this.Bids.Where(o => o.BrokerId == info.BrokerId).FirstOrDefault().IsBrokerSelected = true;
                                        //this.Ofrs.Where(o => o.BrokerId == info.BrokerId).FirstOrDefault().IsBrokerSelected = true;
                                    });

                                    receiver.IsDisabled = false; // 高亮显示
                                }
                                else
                                {
                                    receiver.IsDisabled = true; // 变灰
                                }
                            }
                            else
                            {
                                receiver.IsDisabled = true; //true=被占用
                            }
                        }
                    }
                    else
                    {
                        OccupiedBroker = new List<BrokerInfo>();
                        //// 自己没下单的情况，把别人占用的中介变灰，其他中介高亮显示
                        //PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                        //{
                        //    // 将 Bids 集合中每个项的 IsBrokerSelected 属性设置为 false
                        //    this.Bids.ForEach(bid => bid.IsBrokerSelected = false);

                        //    // 将 Ofrs 集合中每个项的 IsBrokerSelected 属性设置为 false
                        //    this.Ofrs.ForEach(ofr => ofr.IsBrokerSelected = false);
                        //});
                        foreach (var receiver in ChatReceivers)
                        {
                            var info = BrokerInfosByLily.FirstOrDefault(b => b.BrokerId == receiver.Brokerid);
                            if (info != null)
                            {
                                if (info.Occupy)
                                {
                                    if (SelectedReceiver != null)
                                    {
                                        if (SelectedReceiver.Brokerid == receiver.Brokerid)
                                        {
                                            SelectedReceiver = ChatReceivers.FirstOrDefault();
                                        }
                                    }

                                    receiver.IsDisabled = true; // 被别人占用，变灰
                                }
                                else
                                {
                                    receiver.IsDisabled = false; // 未被占用，高亮显示
                                }
                            }
                            else
                            {
                                receiver.IsDisabled = false; // 未占用
                            }
                        }
                    }

                    var chatReceiver = ChatReceivers.FirstOrDefault(o => o.Brokerid == -1);

                    if (chatReceiver != null)
                    {
                        // If an item is found, set IsDisabled to false
                        chatReceiver.IsDisabled = false;
                    }
                }
                catch (Exception ex)
                {
                    AppLog.WriteError("HandleOccupyBrokerInfoMessage 处理" + ex.Message + ex.StackTrace);
                }
            }
        }
        private async void InitPriceAsync()
        {
            DateOnly dtStart = DateOnly.FromDateTime(DateTime.Now);
            var TempTrades = await UserHelper.GetTradeHistoriesAsync(TsCode, dtStart, DateOnly.FromDateTime(DateTime.Now), 1, true);
            if (TempTrades == null || TempTrades.Count() == 0)
            {
                return;
            }
            this.CurrentPrice = TempTrades.LastOrDefault().TradePrice;
            this.Price = CurrentPrice;
        }

        private void WebSocketHelper_QuanYiOrderClientMessageEvent(QuanYiOrderServerResponseClass QSR)
        {
            if(QSR.DataType==QuanYiServerBaseClass.DataTypeEnum.PingCang)
            {
                if (QSR.Guid == CurrentGuid)
                {
                    GlobalQSR = QSR;
                    bResponseReceived = true; 
                }
            }
        }

        private async void InitBroker()
        {
            //var chatReceiversResult = await Task.Run(() =>
            // _dailyData.GetChatReceivers());
            var chatReceiversResult = OrderListViewModel.ChatReceivers;
            ChatReceivers = chatReceiversResult.ToObservableCollection();

            ChatReceivers.Insert(0, new ChatReceiver()
            {
                Brokerid = -1,
                Target = "自动",
                Company = "自动",
                Id = 0
            });


            SelectedReceiver = ChatReceivers[0];

            if(OrderListViewModel.occupyBrokerInfos!=null&&OrderListViewModel.occupyBrokerInfos.Count()>0)
            {
                HandleOccupyBrokerInfoMessage(OrderListViewModel.occupyBrokerInfos);

            }
        }

        private void InitCommand()
        {
            ConfirmPingCangCommand = new DelegateCommand(ConfirmPingCang);
        }
        private QuanYiOrderServerResponseClass qsr;
        private decimal CurrentPrice; //现价
        private Guid CurrentGuid;//唯一Guid
        private bool bResponseReceived = false; //是否收到服务端反馈
        private bool bIsConnected = false; //是否连接到服务端
        private QuanYiOrderServerResponseClass GlobalQSR = new QuanYiOrderServerResponseClass();//服务端返回
        private bool bWaitingforResponse = false;//等服务端反馈？
        private async void ConfirmPingCang()
        {// 生成字符串
            //Growl.InfoGlobal("平仓功能还未实现,请等待");
            if(this.CurrentPrice<0.1M)
            {
                MessageBox.Show("价格异常，请检查");
                return;
            }

            string message = $"类型: {DealType}\n" +
                             $"券码: {TsCode}\n" +
                             $"价格: {Price}\n" +
                             $"量: {Volume}\n" +
                             $"交割日期: {DeliveryDate}";
            //MessageBoxResult result = HandyControl.Controls.MessageBox.Show("是否确认平仓？"+"\r\n"+message, "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

     //       if(result == MessageBoxResult.No)
     //       {
     //           AppLog.WriteInfo("用户取消平仓" + this.UserTradeID);
     //       }

     //       if (result == MessageBoxResult.Yes)
     //       {
     //           AppLog.WriteInfo("用户确认平仓" + this.UserTradeID);


     //           var tempTsInfo = _dailyData.GetBondByCode(TsCode);
     //           this.CurrentPrice = _dailyData.GetLatestPrice(tempTsInfo);

     //           if (DealType=="买入")
     //           {
     //               if (CurrentPrice - Price > 0.01M)
     //               {
     //                   var result1 = MessageBox.Show("下单买价与当前价差超过1BP，不允许下买单", "确认---买单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
     //                   if (result1 == MessageBoxResult.Yes)
     //                   {
     //                       // 用户点击了"是"
     //                       // 执行下单操作
     //                       return;

     //                   }
     //                   else
     //                   {
     //                       return;
     //                   }
     //               }
     //               if (CurrentPrice - Price > 0.0025M)
     //               {
     //                   var result1 = MessageBox.Show("下单买价与当前价差超过0.25BP，是否下买单", "确认---买单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
     //                   if (result1 == MessageBoxResult.Yes)
     //                   {
     //                       // 用户点击了"是"
     //                       // 执行下单操作

     //                   }
     //                   else
     //                   {
     //                       return;
     //                   }
     //               }

     //           }
     //           else
     //           {
     //               if (Price - CurrentPrice > 0.01M)
     //               {
     //                   var result1 = MessageBox.Show("下单卖价与当前价差超过1BP，不允许下卖单", "确认---卖单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
     //                   if (result1 == MessageBoxResult.Yes)
     //                   {
     //                       // 用户点击了"是"
     //                       // 执行下单操作
     //                       return;

     //                   }
     //                   else
     //                   {
     //                       return;
     //                   }
     //               }
     //               if (Price - CurrentPrice > 0.0025M)
     //               {
     //                   var result1 = MessageBox.Show("下单卖价与当前价差超过0.25BP，是否下卖单", "确认---卖单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
     //                   if (result1 == MessageBoxResult.Yes)
     //                   {
     //                       // 用户点击了"是"
     //                       // 执行下单操作

     //                   }
     //                   else
     //                   {
     //                       return;
     //                   }
     //               }

     //           }

     //           string order = string.Empty;
     //           //QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
     //           qsr = new QuanYiOrderServerResponseClass();
     //           UserTrade trade = new UserTrade();
     //           trade.RealTradeIdList = OriginalUserTrade.Children
     //.Where(item => item.RealTradeId.HasValue) // 过滤掉 RealTradeId 为 null 的项
     //.Select(item => item.RealTradeId.Value)   // 提取 RealTradeId 并转换为 int
     //.ToArray();
     //           if (DealType=="买入")
     //           {
                   
     //               string formattedDate = this.DeliveryDate.ToString("M月d日");
     //               //trade.DeliverySpeed = formattedDate + (SelectedOptionJia0 ? "+0" : "+1");

     //               trade.DealType = "bid";
     //               trade.OrderType = UserTrade.UserTradeOrderTypeEnum.Bid;
     //               order = order + "bid ";
     //           }
     //           else
     //           {
     //               string formattedDate = this.DeliveryDate.ToString("M月d日");
     //               //trade.DeliverySpeed = formattedDate + (SelectedOptionJia0 ? "+0" : "+1");
     //               trade.DealType = "ofr";
     //               trade.OrderType = UserTrade.UserTradeOrderTypeEnum.Ofr;
     //               order = order + "ofr ";
     //           }

     //           string dtDate = DeliveryDate.Month.ToString() + "月" + DeliveryDate.Day.ToString() + "日";

     //           CurrentGuid = Guid.NewGuid();
     //           bResponseReceived = false;
     //           AppLog.WriteInfo("SendOrder" + order);
     //           trade.UserID = UserHelper.UserID;
     //           trade.TsCode = TsCode;
     //           trade.Price = Price;
     //           trade.Volume = (int)Volume;
     //           trade.OnHoldVolume = trade.Volume;
     //           trade.DeliveryDate = DateOnly.FromDateTime(DeliveryDate);


     //           ChatReceiver chat = ChatReceivers.FirstOrDefault(x => x.FormattedTarget == SelectedReceiver.FormattedTarget);
     //           //ChatReceiver chat = ChatReceivers.Single(x => x.Target == Target);
     //           trade.ReceiverId = chat.Id;
     //           trade.ChatID = chat.ChatId;
     //           trade.ChannelID = chat.ChannelId;


     //           trade.Target = SelectedReceiver.FormattedTarget;
     //           trade.Guid = CurrentGuid;
     //           trade.Command = order;

     //           trade.BrokerID = chat.Brokerid;
     //           // if (chat==null||chat.Brokerid==-1)
     //           // {
     //           //     trade.BrokerID = null;
     //           // }
     //           //else
     //           // {
     //           //     trade.BrokerID = chat.Id;
     //           // }
     //           //var currentOrderWindow = PrismApplication.Current.Windows.OfType<OrderView>().SingleOrDefault(x => x.IsActive);
     //           //var confirmationDialog = new ConfirmationDialog(trade)
     //           //{
     //           //    Owner = currentOrderWindow, // 设置当前 OrderView 窗口为对话框的 Owner
     //           //    WindowStartupLocation = WindowStartupLocation.CenterOwner // 确保对话框在主窗口之上
     //           //};

               

     //           qsr.Trade = trade;
     //           qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.PingCang;
     //           qsr.Guid = CurrentGuid;
     //           int UserTradeID = 0;

     //           //DialogHelper.ShowLoading("开始创建询价单");
     //           string msg;
     //           try
     //           {


     //               if (!bIsConnected)
     //               {
     //                   IsLoading=true;
     //                   bResponseReceived = false;
     //                   Check(qsr);                   
     //               }
     //               else
     //               {
     //                   AppLog.WriteError($"下单：微信平仓失败,{trade.Command},{trade.Target}");
     //                   return;
     //               }
     //           }
     //           catch (Exception ex)
     //           {
     //               AppLog.WriteError($"下单：平仓失败,{trade.Command},{trade.Target}");
     //           }
     //           finally
     //           {
     //               IsLoading = false;
     //           }

     //           AppLog.WriteInfo($"下单：微信平仓成功,{trade.Command},{trade.Target}");
     //           OrderListViewModel.UpdateFlag = true;
     //       }


            AppLog.WriteInfo("用户确认平仓" + this.UserTradeID);


            //var tempTsInfo = _dailyData.GetBondByCode(TsCode);
            //this.CurrentPrice = _dailyData.GetLatestPrice(tempTsInfo);

            string currentPriceInfo = " 当前价格为" + this.CurrentPrice;
            if (DealType == "买入")
            {
                if (CurrentPrice - Price > 0.01M)
                {
                    var result1 = MessageBox.Show("下单买价与当前价差超过1BP，不允许下买单"+ currentPriceInfo, "确认---买单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result1 == MessageBoxResult.Yes)
                    {
                        // 用户点击了"是"
                        // 执行下单操作
                        return;

                    }
                    else
                    {
                        return;
                    }
                }
                if (CurrentPrice - Price > 0.0025M)
                {
                    var result1 = MessageBox.Show("下单买价与当前价差超过0.25BP，是否下买单", "确认---买单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result1 == MessageBoxResult.Yes)
                    {
                        // 用户点击了"是"
                        // 执行下单操作

                    }
                    else
                    {
                        return;
                    }
                }

            }
            else
            {
                if (Price - CurrentPrice > 0.01M)
                {
                    var result1 = MessageBox.Show("下单卖价与当前价差超过1BP，不允许下卖单" + currentPriceInfo, "确认---卖单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result1 == MessageBoxResult.Yes)
                    {
                        // 用户点击了"是"
                        // 执行下单操作
                        return;

                    }
                    else
                    {
                        return;
                    }
                }
                if (Price - CurrentPrice > 0.0025M)
                {
                    var result1 = MessageBox.Show("下单卖价与当前价差超过0.25BP，是否下卖单", "确认---卖单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result1 == MessageBoxResult.Yes)
                    {
                        // 用户点击了"是"
                        // 执行下单操作

                    }
                    else
                    {
                        return;
                    }
                }

            }

            string order = string.Empty;
            //QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
            qsr = new QuanYiOrderServerResponseClass();
            UserTrade trade = new UserTrade();
            trade.RealTradeIdList = OriginalUserTrade.Children
 .Where(item => item.RealTradeId.HasValue) // 过滤掉 RealTradeId 为 null 的项
 .Select(item => item.RealTradeId.Value)   // 提取 RealTradeId 并转换为 int
 .ToArray();
            if (DealType == "买入")
            {

                string formattedDate = this.DeliveryDate.ToString("M月d日");
                //trade.DeliverySpeed = formattedDate + (SelectedOptionJia0 ? "+0" : "+1");

                trade.DealType = "bid";
                trade.OrderType = UserTrade.UserTradeOrderTypeEnum.Bid;
                order = order + "bid ";
            }
            else
            {
                string formattedDate = this.DeliveryDate.ToString("M月d日");
                //trade.DeliverySpeed = formattedDate + (SelectedOptionJia0 ? "+0" : "+1");
                trade.DealType = "ofr";
                trade.OrderType = UserTrade.UserTradeOrderTypeEnum.Ofr;
                order = order + "ofr ";
            }

            string dtDate = DeliveryDate.Month.ToString() + "月" + DeliveryDate.Day.ToString() + "日";

            CurrentGuid = Guid.NewGuid();
            bResponseReceived = false;
            AppLog.WriteInfo("SendOrder" + order);
            trade.UserID = UserHelper.UserID;
            trade.TsCode = TsCode;
            trade.Price = Price;
            trade.Volume = (int)Volume;
            trade.OnHoldVolume = trade.Volume;
            trade.DeliveryDate = DateOnly.FromDateTime(DeliveryDate);
            if(this.SelectedOptionJia0)
            {
                trade.DeliverySpeed = "0";
            }else
            {
                trade.DeliverySpeed = "1";
            }

            ChatReceiver chat = ChatReceivers.FirstOrDefault(x => x.FormattedTarget == SelectedReceiver.FormattedTarget);
            //ChatReceiver chat = ChatReceivers.Single(x => x.Target == Target);
            trade.ReceiverId = chat.Id;
            trade.ChatID = chat.ChatId;
            trade.ChannelID = chat.ChannelId;


            trade.Target = SelectedReceiver.FormattedTarget;
            trade.Guid = CurrentGuid;
            trade.Command = order;

            trade.BrokerID = chat.Brokerid;
            // if (chat==null||chat.Brokerid==-1)
            // {
            //     trade.BrokerID = null;
            // }
            //else
            // {
            //     trade.BrokerID = chat.Id;
            // }
            //var currentOrderWindow = PrismApplication.Current.Windows.OfType<OrderView>().SingleOrDefault(x => x.IsActive);
            //var confirmationDialog = new ConfirmationDialog(trade)
            //{
            //    Owner = currentOrderWindow, // 设置当前 OrderView 窗口为对话框的 Owner
            //    WindowStartupLocation = WindowStartupLocation.CenterOwner // 确保对话框在主窗口之上
            //};



            qsr.Trade = trade;
            qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.PingCang;
            qsr.Guid = CurrentGuid;
            int UserTradeID = 0;

            //DialogHelper.ShowLoading("开始创建询价单");
            string msg;
            try
            {


                if (!bIsConnected)
                {
                    IsLoading = true;
                    bResponseReceived = false;
                    Check(qsr);
                }
                else
                {
                    AppLog.WriteError($"下单：微信平仓失败,{trade.Command},{trade.Target}");
                    return;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"下单：平仓失败,{trade.Command},{trade.Target}");
            }
            finally
            {
                IsLoading = false;
            }

            AppLog.WriteInfo($"下单：微信平仓成功,{trade.Command},{trade.Target}");
            OrderListViewModel.UpdateFlag = true;
        }

        private async void Check(QuanYiOrderServerResponseClass qsr1)
        {
            OrderListViewModel.websocket.SendResponseToServer(qsr1);
            await WaitForWebSocketResponse(); // 等待 WebSocket 响应

            Messenger.Default.Send(new string("2"));
        }

        private async Task WaitForWebSocketResponse()
        {
            DateTime dtStart = DateTime.Now;
            TimeSpan ts = new TimeSpan();
            ts = DateTime.Now - dtStart;

            while (ts.TotalSeconds < ClientWebSocketHelper.GlobalTimeOut)
            {
                if (bResponseReceived)
                {
                    Growl.InfoGlobal(GlobalQSR.Message);
                    if (GlobalQSR.Code == 0)
                    {
                        //QCT.Id = GlobalQSR.Trade.Id;
                        //QCT.Time = GlobalQSR.Trade.Time;
                        bWaitingforResponse = false;
                        string info = $"券码：{GlobalQSR.Trade.TsCode}" +
                            $"指令：{GlobalQSR.Trade.Command}," +
                            $"中介：{GlobalQSR.Trade.Broker}" +
                            $"类型：{GlobalQSR.Trade.DealType}," +
                            $"清算速度：{GlobalQSR.Trade.DeliveryDate}" +
                            $"询量：{GlobalQSR.Trade.Volume}" +
                            $"价格：{GlobalQSR.Trade.Price}" +
                            $"指令：{GlobalQSR.Trade.OrderType}" +
                            $"状态：{GlobalQSR.Trade.StatusText}" +
                            $"操作人：{GlobalQSR.Trade.UserName}" +
                            $"消息：{GlobalQSR.Message}";

                   
                        if (GlobalQSR.DataType == QuanYiServerBaseClass.DataTypeEnum.Order)
                        {

                            //AllSuccessPlaceOrders.Add(GlobalQSR.Trade);
                            //Growl.SuccessGlobal("新增一条询价单" + info);
                        }

                        if (GlobalQSR.DataType == QuanYiServerBaseClass.DataTypeEnum.Withdrawed)
                        {
                            //Growl.SuccessGlobal("成功撤回。" + GlobalQSR.Message);
                        }
                        if (GlobalQSR.Message == null)
                        {
                            //MessageBox.Show("询价单创建失败" + info, "信息");
                            //AppLog.WriteInfo("询价单创建失败" + info);
                        }
                        else
                        {
                            //MessageBox.Show("成功!" + GlobalQSR.Message, "下单成功");
                            //Growl.SuccessGlobal("下单成功!" + GlobalQSR.Message);
                            //AppLog.WriteInfo("成功!"+GlobalQSR.Message+info);
                        }

                    }//11说明重定向到改价了 传回来一组list可能是多个改价重定向。
                    else if (GlobalQSR.Code == 11)
                    {
                        var changePriceIds = GlobalQSR.ChangePriceIds;
                        var tradeId = GlobalQSR.Trade.UserTradeID;
                        MessageBox.Show("请查看询价单界面作改价操作！"+"\r\n"+GlobalQSR.Message, "提示");
                        var t = GlobalQSR.ChangePriceIds;
                        //RedirectChangePrice(changePriceIds);
                        bWaitingforResponse = false;

                        return;
                    }
                    else
                    {
                        bWaitingforResponse = false;
                        MessageBox.Show(GlobalQSR.Message, "异常提示");
                        return;
                    }
                    bResponseReceived = false;
                    return;
                }

                await Task.Delay(20);
                ts = DateTime.Now - dtStart;
            }

            bWaitingforResponse = false;
            MessageBox.Show("连接服务器超时", "信息");
        }
    }
}
